﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Metadata.Edm;
using Microsoft.VisualStudio.Modeling;
using Framework.DSL;

namespace TesteT4
{
    public partial class Form1 : Form
    {
        string variavelNamespaceMensagem = "Atacadao.DB.Comum.Mensagens";
        string variavelNamespaceTemporario = "Atacadao.DB";

        public Form1()
        {
            InitializeComponent();
        }

        
        

        private void button1_Click(object sender, EventArgs et)
        {
            

            CodeGenerationTools code = new CodeGenerationTools(this);
            MetadataLoader loader = new MetadataLoader(this);
            CodeRegion region = new CodeRegion(this, 1);
            MetadataTools ef = new MetadataTools(this);

            //string inputFile = @"C:\Users\Luis\Documents\Visual Studio 2010\Projects\Atacadao\Atacadao\AtacadaoDB\Atacadao.DB\AtacadaoDB.edmx";
            string inputFile = @"C:\Users\Luis\Documents\Visual Studio 2010\Projects\NaviCar\NaviCar.DB\NaviCarDB.edmx";
            MetadataWorkspace metadataWorkspace = null;
            bool allMetadataLoaded = loader.TryLoadAllMetadata(inputFile, out metadataWorkspace);
            EdmItemCollection ItemCollection = (EdmItemCollection)metadataWorkspace.GetItemCollection(DataSpace.CSpace);
            OriginalValueMembers originalValueMembers = new OriginalValueMembers(allMetadataLoaded, metadataWorkspace, ef);
            string namespaceName = code.VsNamespaceSuggestion();
            string annotationNamespace = "http://schemas.microsoft.com/ado/2009/02/edm/annotation";

            AuxiliarTemplate auxTemplate = new AuxiliarTemplate();

            //EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);

            // The path of a DSL model file:
            string dslModel = @"C:\Users\Luis\Documents\Visual Studio 2010\Projects\Atacadao\Atacadao\AtacadaoDB\Atacadao.DB\FrameworkDSL1.frmDSL";
            // Set up the Store to read your type of model:
            Store store = new Store(
              typeof(FrameworkDSLDomainModel));

            ModeloDados familyTree;

            using (Transaction t = store.TransactionManager.BeginTransaction("Testando"))
            {
                familyTree = FrameworkDSLSerializationHelper.Instance.LoadModel(store, dslModel, null, null, null);
                

                string variavelNamespaceTemporario = "Atacadao.DB";

                
                foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
                {
                    List<AtributosMetadados> listaAtributos = new List<AtributosMetadados>();

                    Entidade classeAlteracao = (from c in familyTree.Entidade where c.Name == entity.Name select c).SingleOrDefault();
                    //AtributosMetadados atributo = new AtributosMetadados { Nome = entity.Name };
           
                    if(classeAlteracao == null)
                    {
                        classeAlteracao = new Entidade(store);
                        classeAlteracao.Name = entity.Name;
                        classeAlteracao.ModeloDados = familyTree;
                        
                    }   

                    
                    foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
                    {
                        if(classeAlteracao.Propriedade.Where(f=>f.Nome == edmProperty.Name).Select(f=>f).SingleOrDefault() == null)
                        {
                            Propriedade auxProp = new Propriedade(store);
                            auxProp.Nome = edmProperty.Name;
                            classeAlteracao.Propriedade.Add(auxProp);
                            
                            //Dropdown list
                            DropDownlist auxDpr = auxTemplate.CriarAtributoDropDown(store, edmProperty, entity.NavigationProperties);
                            if(auxDpr != null) classeAlteracao.DropDownlist.Add(auxDpr);

                            TipoDados auxTipo = auxTemplate.CriarAtributoTipoDados(store, edmProperty);
                            if (auxTipo != null) classeAlteracao.TipoDado.Add(auxTipo);

                            TipoDados atrTipoDados = classeAlteracao.TipoDado.Where(f=>f.Campo == edmProperty.Name).Select(f=>f).SingleOrDefault();
                            DropDownlist atrDrop = classeAlteracao.DropDownlist.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            Obrigatorio atrObrigatorio = classeAlteracao.Obrigatorio.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            MascaraAttribute atrMascara = classeAlteracao.MascaraAttributes.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            CpfCnpjValidator atrCpfCnpj = classeAlteracao.CpfCnpjValidator.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            MaiorQueAttribute atrMaiorQue = classeAlteracao.MaiorQueAttributes.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            MenorQueAttribute atrMenorQue = classeAlteracao.MenorQueAttributes.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            MaiorIgualQueAttribute atrMaiorIgualQue = classeAlteracao.MaiorIgualQueAttributes.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            MenorIgualQueAttribute atrMenorIgualQue = classeAlteracao.MenorIgualQueAttributes.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();
                            DisplayName atrDisplayName = classeAlteracao.DisplayNames.Where(f => f.Campo == edmProperty.Name).Select(f => f).SingleOrDefault();

                            if (!ef.IsNullable(edmProperty))
                            {
                                Obrigatorio obr = new Obrigatorio(store);
                                classeAlteracao.Obrigatorio.Add(obr);
                            }

                            auxTemplate.EscreverAtributoTipoDado(atrTipoDados, atrDrop);

                        }                                
                    }


                    foreach (EdmProperty edmProperty in entity.Properties.Where(p => p.TypeUsage.EdmType is PrimitiveType && p.DeclaringType == entity))
                    {
                        if (classeAlteracao.Propriedade.Where(f => f.Nome == edmProperty.Name).Select(f => f).SingleOrDefault() == null)
                        {
                            Propriedade auxProp = new Propriedade(store);
                            classeAlteracao.Propriedade.Add(auxProp);
                            auxProp.Nome = edmProperty.Name;
                        }

                        if (auxTemplate.TemDropDownlist(edmProperty, entity.NavigationProperties))
                        {
                            //auxTemplate.EscreverDropDownlist(edmProperty, entity.NavigationProperties);

                            //atributo.DropDownlist = new DropDown { Codigo = entity.Name };
                        }


                    }

                }

                t.Commit();
            }


            try
            {
              SerializationResult result = new SerializationResult();
              FrameworkDSLSerializationHelper.Instance
                .SaveModel(result, familyTree, dslModel);
              // Report any error:
              if (result.Failed)
              {
                foreach (SerializationMessage message in result)
                {
                  Console.WriteLine(message);
                }
              }
            }
            catch (System.IO.IOException ex)
            { MessageBox.Show(ex.ToString()); }

            //fileManager.Process();

        }
        
    }
}
